from multiprocessing import Pool
import os, time, random


def worker(msg):
    t_start = time.time()
    print("%s 开始执行，进程号为 %d" % (msg, os.getpid()))
    # random.random() 生成 0-1 之间的随机浮点数
    time.sleep(random.random()*2)
    t_stop = time.time()
    print(msg, "执行完毕，耗时 %.2f" % (t_stop - t_start))


def main():
    pool = Pool(3)  # 定义一个进程池，最大进程数是3
    for i in range(10):
        pool.apply_async(worker, (i,))

    print("---start---")
    pool.close()  # 关闭线程池
    pool.join()  # 让主线程等待线程池中的任务全部执行完成，必须放在 close() 之后
    print("---end---")


if __name__ == '__main__':
    main()
    